package com.raysdata.smartcity.flow.activiti.dao;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.ProcessEngineImpl;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 流程DAO
 * Created by liux on 2016/12/08.
 */
@Component
public class ProcessDao{

    Log log = LogFactory.getLog(ProcessDao.class);
    @Autowired
    public ProcessEngine processEngine ;
    @Autowired
    public RepositoryService repositoryService;
    @Autowired
    public RuntimeService runtimeService;
    @Autowired
    public HistoryService historyService;
    @Autowired
    public IdentityService identityService;
    @Autowired
    public  TaskService taskService;

    public String createProcessInstance(String proc_def_id,String business,Map map,String user_id){
        try {
            //设置流程启动人：当前登录人
            identityService.setAuthenticatedUserId(user_id);
            //启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(proc_def_id, business, map);

            //processEngine.close();

            return processInstance.getProcessInstanceId().toString();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 签收任务
     *
     * @param task_id          任务ID
     * @param currentLoginUser 操作人
     * @return
     */
    public int assigned(String task_id, String currentLoginUser) {
        try {
            taskService.claim(task_id, currentLoginUser);
            //processEngine.close();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 根据任务ID查询任务
     * @param task_id
     * @return
     */
    public Task getTaskById(String task_id) {
        try {
            Task task=taskService.createTaskQuery().taskId(task_id).singleResult();
            //processEngine.close();
            return task;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据流程实例ID，获取下一环节信息
     *
     * @param process_inst_id 流程实例ID
     * @return
     */
    public Map<String, String> getNextNodeInfo1(String process_inst_id, String approveResult) {

        try {
            TaskDefinition taskDefinition = nextTaskDefinition1(runtimeService, repositoryService, historyService, process_inst_id, approveResult);
            if (taskDefinition != null) {
                Map<String, String> map = new HashMap<String, String>();
                //下一环节key
                map.put("nextNodeKey", taskDefinition.getKey());
                //下一环节名称
                if(taskDefinition.getNameExpression()==null){
                    map.put("nextNodeName","结束流程");
                }else{
                    map.put("nextNodeName",taskDefinition.getNameExpression().getExpressionText());
                }
                taskDefinition=null;

                return map;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 根据流程实例ID，获取下一环节信息
     * @param process_inst_id 流程实例ID
     * @return
     */
    public List<Map<String,String>> getNextNodeInfoList1(String process_inst_id,String approveResult) {

        try {
            List<TaskDefinition> taskDefinitions =nextTaskDefinitionList1(runtimeService,repositoryService,historyService,process_inst_id,approveResult);
            List<Map<String,String>> list=new ArrayList<Map<String,String>>();
            if(taskDefinitions!=null){
                for(TaskDefinition task:taskDefinitions){
                    Map<String,String> map =new HashMap<String,String>();
                    //下一环节key
                    map.put("nextNodeKey",task.getKey());

                    list.add(map);
                }
                return list;
            }else{
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 处理任务
     *
     * @param task_id      任务ID
     * @param proc_inst_id 流程实例ID
     * @param map          变量MAP
     * @param comment      处理意见
     * @param currentUser  处理人
     * @return
     */
    public int complete(String task_id, String proc_inst_id, Map<String, Object> map, String comment, String currentUser) {

        try {

            Authentication.setAuthenticatedUserId(currentUser);
            taskService.addComment(task_id, proc_inst_id, comment);
            taskService.complete(task_id, map);
           //processEngine.close();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 获得流程定义的所有节点信息
     *
     * @param pdId
     */
    public void findNodeByPdId(RepositoryService repositoryService, String pdId) {
        BpmnModel model = repositoryService.getBpmnModel(pdId);
        if (model != null) {
            Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
            for (FlowElement e : flowElements) {
                System.out.println("flowelement id:" + e.getId() + "  name:" + e.getName() + "   class:" + e.getClass().toString());
            }
        }
    }

    /**
     * 根据当前节点获取下一节点信息
     *
     * @param runtimeService
     * @param repositoryService
     * @param historyService
     * @param procInstId
     * @return
     */
    public TaskDefinition nextTaskDefinition1(RuntimeService runtimeService, RepositoryService repositoryService, HistoryService historyService, String procInstId, String exclusiveGatewayValue) {
        //流程标示
        String processDefinitionId = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId();
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(processDefinitionId);
        //执行实例
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        //当前实例的执行到哪个节点
        String activitiId = execution.getActivityId();
        //获得当前任务的所有节点
        List<ActivityImpl> activitiList = def.getActivities();

        String id = null;
        for (ActivityImpl activityImpl : activitiList) {
            id = activityImpl.getId();
            if (activitiId.equals(id)) {
                System.out.println("当前任务：" + activityImpl.getProperty("name"));
                return nextTaskDefinition1(activityImpl, activityImpl.getId(), exclusiveGatewayValue);
            }
        }
        return null;
    }

    /**
     * 下一个任务节点
     *
     * @param activityImpl
     * @param activityId
     * @param elString
     * @return
     */
    private TaskDefinition nextTaskDefinition1(ActivityImpl activityImpl, String activityId, String elString) {
        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior()).getTaskDefinition();
            //taskDefinition.getCandidateGroupIdExpressions().toArray();
            return taskDefinition;
        } else {
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;

            for (PvmTransition tr : outTransitions) {
                PvmActivity ac = tr.getDestination(); //获取线路的终点节点

                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition1((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {

                        for (PvmTransition tr1 : outTransitionsTemp) {
                            Object s = tr1.getProperty("conditionText");

                            if (elString.equals(StringUtils.trim(s.toString()))) {
                                return nextTaskDefinition1((ActivityImpl) tr1.getDestination(), activityId, elString);

                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    if ("parallelGateway".equals(tr.getSource().getProperty("type").toString())){
                        return nextTaskDefinition1((ActivityImpl) tr.getDestination(), ac.getId(), elString);
                    }else{
                        return ((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition();
                    }
                } else if ("parallelGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition1((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {
                        System.out.println("查找下一节点type:" + ac.getProperty("type"));
                    }
                    return null;
                }else {
                    System.out.println("查找下一节点type:" + ac.getProperty("type"));
                }
            }
            return null;
        }
    }


    /**
     * 下一个任务节点
     *
     * @param activityImpl
     * @param activityId
     * @param elString
     * @return
     */
    private List<TaskDefinition> nextTaskDefinitionList1(ActivityImpl activityImpl, String activityId, String elString) {
        List<TaskDefinition> taskDefinitionList = new ArrayList<TaskDefinition>();

        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior()).getTaskDefinition();
            //taskDefinition.getCandidateGroupIdExpressions().toArray();
            taskDefinitionList.add(taskDefinition);
            return taskDefinitionList;
        } else {
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;

            for (PvmTransition tr : outTransitions) {
                PvmActivity ac = tr.getDestination(); //获取线路的终点节点

                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinitionList1((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {

                        for (PvmTransition tr1 : outTransitionsTemp) {
                            Object s = tr1.getProperty("conditionText");
                            if (elString.equals(StringUtils.trim(s.toString()))) {
                                return nextTaskDefinitionList1((ActivityImpl) tr1.getDestination(), activityId, elString);
                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    taskDefinitionList.add(((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition());
                    return taskDefinitionList;
                } else if ("parallelGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinitionList1((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {

                        for (PvmTransition tr1 : outTransitionsTemp) {
                            PvmActivity ac1 = tr1.getDestination(); //获取线路的终点节点

                            if ("userTask".equals(ac1.getProperty("type"))) {
                                taskDefinitionList.add(((UserTaskActivityBehavior) ((ActivityImpl) ac1).getActivityBehavior()).getTaskDefinition());
                            }
                        }
                        return taskDefinitionList;
                    }
                } else {
                    System.out.println("查找下一节点type:" + ac.getProperty("type"));
                }
            }
            return null;
        }
    }

    /**
     * 根据当前节点获取下一节点信息
     * @param runtimeService
     * @param repositoryService
     * @param historyService
     * @param procInstId
     * @return
     */
    public List<TaskDefinition> nextTaskDefinitionList1(RuntimeService runtimeService, RepositoryService repositoryService, HistoryService historyService, String procInstId,String exclusiveGatewayValue){
        //流程标示
        String processDefinitionId = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId();
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl)repositoryService).getDeployedProcessDefinition(processDefinitionId);
        //执行实例
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        //当前实例的执行到哪个节点
        String activitiId = execution.getActivityId();
        //获得当前任务的所有节点
        List<ActivityImpl> activitiList = def.getActivities();

        String id = null;
        for(ActivityImpl activityImpl:activitiList){
            id = activityImpl.getId();
            if(activitiId.equals(id)){
                System.out.println("当前任务："+activityImpl.getProperty("name"));
                List<TaskDefinition> taskDefinitionList=nextTaskDefinitionList1(activityImpl, activityImpl.getId(),exclusiveGatewayValue);
                return taskDefinitionList;
            }

        }
        return null;
    }


    //=====================================================以下页面显示专用接口================================================================================

    private Map<String,String> nextTaskDefinition(ActivityImpl activityImpl, String activityId, String elString) {
        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior()).getTaskDefinition();
            Map<String,String>  map=new HashMap<String,String>();
            map.put("nextNodeKey",taskDefinition.getKey());
            map.put("nextNodeName",taskDefinition.getNameExpression().getExpressionText());
            return map;
        } else if ("endEvent".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())){
            Map<String,String>  map=new HashMap<String,String>();
            map.put("nextNodeKey","End");
            map.put("nextNodeName","结束流程");
            return map;
        }else{
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;

            for (PvmTransition tr : outTransitions) {
                PvmActivity ac = tr.getDestination(); //获取线路的终点节点

                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {

                        for (PvmTransition tr1 : outTransitionsTemp) {
                            Object s = tr1.getProperty("conditionText");

                            if (elString.equals(StringUtils.trim(s.toString()))) {
                                return nextTaskDefinition((ActivityImpl) tr1.getDestination(), activityId, elString);

                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    if ("parallelGateway".equals(tr.getSource().getProperty("type").toString())){
                        return nextTaskDefinition((ActivityImpl) tr.getDestination(), ac.getId(), elString);
                    }else{
                        Map<String,String>  map=new HashMap<String,String>();
                        map.put("nextNodeKey",((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition().getKey());
                        map.put("nextNodeName",((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition().getNameExpression().getExpressionText());
                        return map;
                    }
                } else if ("parallelGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {
                        System.out.println("查找下一节点type:" + ac.getProperty("type"));
                    }
                    return null;
                }else if ("endEvent".equals(ac.getProperty("type"))){
                    Map<String,String>  map=new HashMap<String,String>();
                    map.put("nextNodeKey","End");
                    map.put("nextNodeName","结束流程");
                    return map;
                }else {
                    System.out.println("查找下一节点type:" + ac.getProperty("type"));
                }
            }

            return null;
        }
    }


    public Map<String,String> nextTaskDefinition(RuntimeService runtimeService, RepositoryService repositoryService, HistoryService historyService, String procInstId, String exclusiveGatewayValue) {
        //流程标示
        String processDefinitionId = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId();
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(processDefinitionId);
        //执行实例
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        //当前实例的执行到哪个节点
        String activitiId = execution.getActivityId();
        //获得当前任务的所有节点
        List<ActivityImpl> activitiList = def.getActivities();

        String id = null;
        for (ActivityImpl activityImpl : activitiList) {
            id = activityImpl.getId();
            if (activitiId.equals(id)) {
                System.out.println("当前任务：" + activityImpl.getProperty("name"));
                return nextTaskDefinition(activityImpl, activityImpl.getId(), exclusiveGatewayValue);
            }
        }
        return null;
    }

    /**
     * 根据流程实例ID，获取下一环节信息
     *
     * @param process_inst_id 流程实例ID
     * @return
     */
    public Map<String, String> getNextNodeInfo(String process_inst_id, String approveResult) {

        try {
            Map<String,String> map = nextTaskDefinition(runtimeService, repositoryService, historyService, process_inst_id, approveResult);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public List<Map<String,String>> getNextNodeInfoList(String process_inst_id,String approveResult) {

        try {
            List<Map<String,String>> list =nextTaskDefinitionList(runtimeService,repositoryService,historyService,process_inst_id,approveResult);
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    private List<Map<String,String>> nextTaskDefinitionList(ActivityImpl activityImpl, String activityId, String elString) {
        List<Map<String,String>> taskDefinitionList = new ArrayList<Map<String,String>>();

        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior()).getTaskDefinition();
            Map<String,String>  map=new HashMap<String,String>();
            map.put("nextNodeKey",taskDefinition.getKey());
            map.put("nextNodeName",taskDefinition.getNameExpression().getExpressionText());
            taskDefinitionList.add(map);
            return taskDefinitionList;
        } else {
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;

            for (PvmTransition tr : outTransitions) {
                PvmActivity ac = tr.getDestination(); //获取线路的终点节点

                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinitionList((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {

                        for (PvmTransition tr1 : outTransitionsTemp) {
                            Object s = tr1.getProperty("conditionText");
                            if (elString.equals(StringUtils.trim(s.toString()))) {
                                return nextTaskDefinitionList((ActivityImpl) tr1.getDestination(), activityId, elString);
                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    Map<String,String>  map=new HashMap<String,String>();
                    map.put("nextNodeKey",((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition().getKey());
                    map.put("nextNodeName",((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition().getNameExpression().getExpressionText());
                    taskDefinitionList.add(map);
                    return taskDefinitionList;
                } else if ("parallelGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinitionList((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId, elString);
                    } else if (outTransitionsTemp.size() > 1) {

                        for (PvmTransition tr1 : outTransitionsTemp) {
                            PvmActivity ac1 = tr1.getDestination(); //获取线路的终点节点

                            if ("userTask".equals(ac1.getProperty("type"))) {
                                Map<String,String>  map=new HashMap<String,String>();
                                map.put("nextNodeKey",((UserTaskActivityBehavior) ((ActivityImpl) ac1).getActivityBehavior()).getTaskDefinition().getKey());
                                map.put("nextNodeName",((UserTaskActivityBehavior) ((ActivityImpl) ac1).getActivityBehavior()).getTaskDefinition().getNameExpression().getExpressionText());
                                taskDefinitionList.add(map);
                            }
                        }
                        return taskDefinitionList;
                    }
                } else {
                    System.out.println("查找下一节点type:" + ac.getProperty("type"));
                }
            }
            return null;
        }
    }

    /**
     * 根据当前节点获取下一节点信息
     * @param runtimeService
     * @param repositoryService
     * @param historyService
     * @param procInstId
     * @return
     */
    public List<Map<String,String>> nextTaskDefinitionList(RuntimeService runtimeService, RepositoryService repositoryService, HistoryService historyService, String procInstId,String exclusiveGatewayValue){
        //流程标示
        String processDefinitionId = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId();
        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl)repositoryService).getDeployedProcessDefinition(processDefinitionId);
        //执行实例
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        //当前实例的执行到哪个节点
        String activitiId = execution.getActivityId();
        //获得当前任务的所有节点
        List<ActivityImpl> activitiList = def.getActivities();

        String id = null;
        for(ActivityImpl activityImpl:activitiList){
            id = activityImpl.getId();
            if(activitiId.equals(id)){
                System.out.println("当前任务："+activityImpl.getProperty("name"));
                List<Map<String,String>> taskDefinitionList=nextTaskDefinitionList(activityImpl, activityImpl.getId(),exclusiveGatewayValue);
                return taskDefinitionList;
            }

        }
        return null;
    }

    /**
     * 获取流程图片--只获取当前活动节点
     * @param proc_def_id
     * @return
     */
    public Map<String, Object> getCurrentActivityCoordinates(String proc_def_id,String proc_inst_id) {
        Map<String, Object> coordinates = new HashMap<String, Object>();
        //  获取到当前活动的ID
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(proc_inst_id).singleResult();
            if(pi!=null){
                String currentActivitiId = pi.getActivityId();
                //  获取到流程定义
                ProcessDefinitionEntity pd = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(proc_def_id);
                // 使用流程定义通过currentActivitiId得到活动对象
                ActivityImpl activity = pd.findActivity(currentActivitiId);
                //  获取活动的坐标
                coordinates.put("x", activity.getX());
                coordinates.put("y", activity.getY());
                coordinates.put("width", activity.getWidth());
                coordinates.put("height", activity.getHeight());
            }
        return coordinates;
    }

    /**
     * 根据流程定义ID获取流程定义
     * @param proc_def_id
     * @return
     */
    public ProcessDefinition getProcessDefinitionById(String proc_def_id) {
        // 通过pdid获取流程定义对象
        ProcessDefinition pd = repositoryService.getProcessDefinition(proc_def_id);
        return pd;
    }

    /**
     * 获取流程走过的线
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */

    public List getHighLightedFlows(ProcessDefinitionEntity processDefinitionEntity,List<HistoricActivityInstance> historicActivityInstances) {
        // 用以保存高亮的线flowId
        List highFlows = new ArrayList();
        // 对历史流程节点进行遍历
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {
            // 得到节点定义的详细信息
            ActivityImpl activityImpl = processDefinitionEntity.findActivity(historicActivityInstances.get(i).getActivityId());
            // 用以保存后需开始时间相同的节点
            List sameStartTimeNodes = new ArrayList();
            // 将后面第一个节点放在时间相同节点的集合里
            ActivityImpl sameActivityImpl1 = processDefinitionEntity.findActivity(historicActivityInstances.get(i + 1).getActivityId());

            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances.get(j); // 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances.get(j + 1); // 后续第二个节点
                // 如果第一个节点和第二个节点开始时间相同保存
                if (activityImpl1.getStartTime().equals(activityImpl2.getStartTime())) {
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity.findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    break;
                }
            }
            // 取出节点的所有出去的线
            List<PvmTransition> pvmTransitions = activityImpl.getOutgoingTransitions();
            // 对所有的线进行遍历
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition.getDestination();
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }
    /**
     * 获取流程图片--获取所有走过的节点和线
     * @param proc_def_id
     * @return
     */
    public Map<String, Object> getActivityCoordinates(String proc_def_id,String proc_inst_id) {
        Map<String, Object> coordinates = new HashMap<String, Object>();
        // 获取流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(proc_inst_id).active().singleResult();
        if (processInstance != null) {

            BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
            List<HistoricActivityInstance> activityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(proc_inst_id).orderByHistoricActivityInstanceStartTime().asc().list();

            List activitiIds = new ArrayList();
            List flowIds = new ArrayList();

            ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                    .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
            // 获取流程走过的线 (getHighLightedFlows是下面的方法)
            flowIds = getHighLightedFlows(processDefinition,activityInstances);
            for (HistoricActivityInstance hai: activityInstances) {
                activitiIds.add(hai.getActivityId());// 获取流程走过的节点
            }

            coordinates.put("bpmnModel",bpmnModel);
            coordinates.put("activitiIds",activitiIds);
            coordinates.put("flowIds",flowIds);

        }else{
            BpmnModel bpmnModel = repositoryService.getBpmnModel(proc_def_id);
            List<HistoricActivityInstance> activityInstances = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(proc_inst_id).orderByHistoricActivityInstanceStartTime().asc().list();

            List activitiIds = new ArrayList();
            List flowIds = new ArrayList();

            ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                    .getDeployedProcessDefinition(proc_def_id);
            // 获取流程走过的线 (getHighLightedFlows是下面的方法)
            flowIds = getHighLightedFlows(processDefinition,activityInstances);
            for (HistoricActivityInstance hai: activityInstances) {
                activitiIds.add(hai.getActivityId());// 获取流程走过的节点
            }

            coordinates.put("bpmnModel",bpmnModel);
            coordinates.put("activitiIds",activitiIds);
            coordinates.put("flowIds",flowIds);
        }
        return coordinates;
    }


}
